package com.project.poetry.service.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.poetry.common.config.ConfigProperties;
import com.project.poetry.common.constant.ConstantValue;
import com.project.poetry.common.util.CommonUtil;
import com.project.poetry.service.entity.dto.user.SaveDetailUserDTO;
import com.project.poetry.service.entity.po.user.UserPO;
import com.project.poetry.service.mapper.UserMapper;
import com.project.poetry.service.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 用户信息业务层实现类
 * @author mengxj
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements UserService {

    @Resource
    private ConfigProperties configProperties;

    @Override
    public void saveDetail(SaveDetailUserDTO user) {
        Integer nameMaxLength = this.configProperties.getNameMaxLength();
        CommonUtil.checkThrow(name -> name.length() > nameMaxLength, user.getUsername(),
                ConstantValue.REG_ERROR_STATUS_CODE,String.format("用户名不可超过 %d 位！！！", nameMaxLength));
        UserPO po = super.getById(user.getId());
        String password = user.getPassword();
        String md5Password = CommonUtil.md5String(password);
        boolean updatePassword = md5Password.equals(po.getPassword());
        BeanUtils.copyProperties(user, po);
        po.setRealPassword(password);
        po.setPassword(md5Password);
        super.updateById(po);
        if(updatePassword){
            CommonUtil.saveUser(po);
        }else{
            CommonUtil.logout();
        }
    }
}
